<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-18 16:34:54
 * @LastEditTime: 2022-05-20 22:23:22
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
-->
<template>
  <el-dialog
    :model-value="modelValue"
    :title="$t('role.assignPermissions')"
    :before-close="onClose"
  >
    <el-tree
      :data="permissionsData"
      check-strictly
      node-key="id"
      :default-checked-keys="checkedPermissions"
      default-expand-all
      ref="permissionRef"
      :props="defaultProps"
      show-checkbox
    />
    <template #footer>
      <el-button @click="onClose">
        {{$t('universal.cancel')}}</el-button>
      <el-button
        type="primary"
        @click="onOk"
      >{{$t('universal.confirm')}}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { watch, ref } from 'vue'
import { getRolePermission, getAllPermission, updateRolePermission } from '@/api/role'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
// eslint-disable-next-line no-undef
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  roleId: {
    type: [String, Number],
    required: true
  }
})
const permissionsData = ref([])
const checkedPermissions = ref([])
const permissionRef = ref(null)

const init = async () => {
  permissionsData.value = await getAllPermission()
  permissionRef.value.setCheckedKeys(await getRolePermission(props.roleId))
}
// eslint-disable-next-line no-undef
const emits = defineEmits(['update:modelValue'])

const i18n = useI18n()
const onOk = async () => {
  await updateRolePermission({ permissions: permissionRef.value.getCheckedKeys(), roleId: props.roleId })
  ElMessage.success(i18n.t('role.updateRoleSuccess'))
  onClose()
}
const onClose = () => {
  emits('update:modelValue', false)
}
watch(() => props.roleId, () => init())
const defaultProps = {
  children: 'children',
  label: 'permissionName'
}
</script>

<style lang='scss' scoped>
</style>
